//全局唯一模态层
import ModalConstructor from "./modal.vue";
import { h, render } from "vue";
import { DialogOper } from "../dialog/dialog.type";
interface ModalType {
  container: Element | null;
  items: DialogOper[];
  [key: string]: any;
}
const Modal: ModalType = {
  zIndex: null,
  container: null,
  items: [],
  vm: null,
  init: function () {
    if (this.vm) return;
    this.container = document.createElement("div");
    const vnode = h(ModalConstructor);
    render(vnode, this.container);
    if (this.container.firstElementChild) {
      document.body.appendChild(this.container.firstElementChild);
    }
    this.vm = vnode.component;
  },
  destroy() {
    if (!this.container) return;
    render(null, this.container);
    this.container = null;
    this.vm = null;
  },
  _check() {
    if (!this.vm) {
      throw "Model is not init,please start `Model.init()` first";
    }
  },
  _push(item: DialogOper) {
    const items = this.items;
    const len = items.length;
    if (len > 0) {
      const last = items[len - 1];
      last.setZIndex(Modal.zIndex);
    }
    items.push(item);
  },
  push(item: DialogOper) {
    // console.log('push');
    this._check();
    const items = this.items;
    const len = items.length;
    if (len === 0) {
      this.vm.proxy.show = true;
    }
    this._push(item);
  },
  pop() {
    // console.log('pop');
    this._check();
    const items = this.items;
    if (items.length === 0) return;
    items.pop();
    const len = items.length;
    if (len > 0) {
      items[len - 1].setZIndex("");
    } else {
      this.vm.proxy.show = false;
    }
  },
  //当dialog destroy的时候，必须调用该方法移除相应item
  remove(id: number) {
    // console.log('remove');
    const items = this.items;
    const len = items.length;
    if (len === 0) return;
    if (id === items[len - 1].id) {
      this.pop();
    } else {
      for (let i = 0; i < len - 1; i++) {
        if (items[i].id === id) {
          items.splice(i, 1);
          break;
        }
      }
    }
  },
};
export default Modal;
